package com.codebox.common.http;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.IOException;
import java.util.HashSet;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * 首次请求，保存Cookie 到SharedPreferences 的拦截器
 *
 * @author Able
 * @date 2018/12/13
 */
public class SaveCookiesInterceptor implements Interceptor {
    private static final String COOKIE_PREF = "cookies_prefs";
    private Context mContext;

    public SaveCookiesInterceptor(Context context) {
        mContext = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
            }

            SharedPreferences.Editor config =
                    mContext.getSharedPreferences(COOKIE_PREF, Context.MODE_PRIVATE).edit();
            config.putStringSet("cookie", cookies);
            config.apply();
        }

        return originalResponse;
    }

}
